package com.itheima.interceptor;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author by itheima
 * @Date 2022/4/28
 * @Description 定义拦截类
 */
public class ProjectInterceptor implements HandlerInterceptor {
    /**
     * 前置增强：在处理器方法执行前执行
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 当前拦截的方法的封装，类似于：ProcessdingJoinPoint
     * @return true:放行资源，不被阻断 false:阻断资源,阻断控制器方法、postHandle、afterCompletion 3个方法都会被阻断
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

       if(handler instanceof HandlerMethod){
           HandlerMethod hand = (HandlerMethod) handler;
           //获取当前拦截的bean对象：controller
           Object bean = hand.getBean();
           //获取拦截的方法
           Method method = hand.getMethod();
       }

        System.out.println("preHandler run....");
        return false;
    }

    /**
     * 在处理器方法执行之后执行
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 当前拦截的方法的封装，类似于：ProcessdingJoinPoint
     * @param modelAndView 就是对视图资源+model数据的封装，如果仅仅响应前端json数据，没有页面资源，则默认是null
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandler");
    }

    /**
     * 最终执行的方法
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 当前拦截的方法的封装，类似于：ProcessdingJoinPoint
     * @param ex 如果抛出异常，也在直接获取异常对象
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion run....");
    }
}
